import {
  host,
  SERIAL
} from '../config.js'
import {
  message
} from './message.js'
export default class UploadImg {
  /**
   * [constructor description]
   * @param  {[Array]} files [chooseImg选中的tempFilePaths]
   * @param  {[Object]} json  [success每上传成功一张调用 complete全部上传完成调用]
   * @return {[void]}       [description]
   */
  constructor(files, json) {
    if (!Array.isArray(files)) {
      throw new Error('Class UploadImg parameter must be an array');
    }
    let _this = this;
    _this.data = [];
    _this.fn = json.success;
    _this.complete = json.complete;
    _this.files = files;
    _this.fileLen = _this.files.length;
    _this.curIndex = 0;
    // uni.showLoading({
    //     title: global.i18n['上传中']
    // });
    uni.showLoading({
      title: '上传中',
      mask: true
    })
    setTimeout(res => {
      _this.upload();
    }, 300)

  }

  upload() {
    let _this = this;
    uni.uploadFile({
      url: host + '/api' + global.apiUrls.UPLOAD_IMAGE_URL,
      filePath: this.files[this.curIndex].path,
      name: 'file',
      header: {
        'user-token': global.token || '',
        "Authorization": 'Bearer ' + global.token || '',
        'Accept-Language': global.locale,
        'Accept-Serial': SERIAL,
      },
      formData: {
        folderName: '11'
      },
      success: res => {

        let data = JSON.parse(res.data);
        console.log(data)
        if (data.code == 0) {
          uni.hideLoading()
          console.log("wedsddfsdsf1111", data);
          if (Array.isArray(data.data)) {
            this.data.push(data.data[0]);
          } else {
            this.data.push(data.data);
          }
          if (this.fn) this.fn(this.data);
        } else {
          message.info(global.i18n['图片上传失败，请重试'])
        }
      },
      complete: () => {
        this.curIndex++; // 这个图片执行完上传后，开始上传下一张
        if (this.curIndex == this.fileLen) { // 当图片传完时，停止调用
          this.complete(this.data);
          uni.hideLoading()
        } else { // 若图片还没有传完，则继续调用函数
          this.upload();
        }
      }
    });
  }
}
